<template>
  <div class="students">
    <el-card>
      <div slot="header">
        <span>学员管理</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="showAddDialog">
          <i class="el-icon-plus"></i> 新增学员
        </el-button>
      </div>
      
      <!-- 搜索栏 -->
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="6">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索昵称/邮箱"
            prefix-icon="el-icon-search"
            clearable
          ></el-input>
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchStatus" placeholder="选择状态" clearable>
            <el-option label="正常" value="active"></el-option>
            <el-option label="封禁" value="banned"></el-option>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchLevel" placeholder="选择等级" clearable>
            <el-option label="新手" value="beginner"></el-option>
            <el-option label="进阶" value="intermediate"></el-option>
            <el-option label="高级" value="advanced"></el-option>
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-col>
      </el-row>

      <!-- 学员列表 -->
      <el-table :data="filteredStudents" border style="width: 100%">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="avatar" label="头像" width="80" align="center">
          <template slot-scope="scope">
            <el-avatar :src="scope.row.avatar" :size="40">
              <img src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="nickname" label="昵称" width="120"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="200"></el-table-column>
        <el-table-column prop="level" label="等级" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="getLevelTagType(scope.row.level)">{{ getLevelText(scope.row.level) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="studyTime" label="学习时长" width="120" align="center">
          <template slot-scope="scope">
            {{ formatStudyTime(scope.row.studyTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="questionCount" label="做题数量" width="100" align="center"></el-table-column>
        <el-table-column prop="correctRate" label="正确率" width="100" align="center">
          <template slot-scope="scope">
            <span :style="{ color: scope.row.correctRate >= 80 ? '#67C23A' : scope.row.correctRate >= 60 ? '#E6A23C' : '#F56C6C' }">
              {{ scope.row.correctRate }}%
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginTime" label="最后登录" width="180"></el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 'active' ? 'success' : 'danger'">
              {{ scope.row.status === 'active' ? '正常' : '封禁' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button 
              size="mini" 
              :type="scope.row.status === 'active' ? 'danger' : 'success'"
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.status === 'active' ? '封禁' : '启用' }}
            </el-button>
            <el-button size="mini" type="info" @click="handleViewDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 20px; text-align: right;"
      ></el-pagination>
    </el-card>

    <!-- 新增/编辑学员对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px">
      <el-form :model="studentForm" :rules="studentRules" ref="studentForm" label-width="100px">
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="studentForm.avatar" :src="studentForm.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="studentForm.nickname" placeholder="请输入昵称"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="studentForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!studentForm.id">
          <el-input v-model="studentForm.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="等级" prop="level">
          <el-select v-model="studentForm.level" placeholder="请选择等级">
            <el-option label="新手" value="beginner"></el-option>
            <el-option label="进阶" value="intermediate"></el-option>
            <el-option label="高级" value="advanced"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="studentForm.status">
            <el-radio value="active">正常</el-radio>
            <el-radio value="banned">封禁</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            v-model="studentForm.remark"
            placeholder="请输入备注"
            :rows="3"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 学员详情对话框 -->
    <el-dialog title="学员详情" :visible.sync="detailDialogVisible" width="800px">
      <div v-if="detailStudent" class="student-detail">
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="detail-section">
              <h4>基本信息</h4>
              <p><strong>昵称：</strong>{{ detailStudent.nickname }}</p>
              <p><strong>邮箱：</strong>{{ detailStudent.email }}</p>
              <p><strong>等级：</strong>{{ getLevelText(detailStudent.level) }}</p>
              <p><strong>状态：</strong>{{ detailStudent.status === 'active' ? '正常' : '封禁' }}</p>
              <p><strong>注册时间：</strong>{{ detailStudent.createTime }}</p>
              <p><strong>最后登录：</strong>{{ detailStudent.lastLoginTime }}</p>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-section">
              <h4>学习统计</h4>
              <p><strong>学习时长：</strong>{{ formatStudyTime(detailStudent.studyTime) }}</p>
              <p><strong>做题数量：</strong>{{ detailStudent.questionCount }}</p>
              <p><strong>正确率：</strong>{{ detailStudent.correctRate }}%</p>
              <p><strong>连续学习：</strong>{{ detailStudent.streakDays }}天</p>
              <p><strong>获得徽章：</strong>{{ detailStudent.badges }}个</p>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-section">
              <h4>学习进度</h4>
              <div v-for="(progress, index) in detailStudent.progress" :key="index">
                <p><strong>{{ progress.category }}：</strong>{{ progress.completed }}/{{ progress.total }}</p>
                <el-progress :percentage="(progress.completed / progress.total) * 100" :stroke-width="8"></el-progress>
              </div>
            </div>
          </el-col>
        </el-row>
        
        <div class="detail-section" style="margin-top: 20px;">
          <h4>最近学习记录</h4>
          <el-table :data="detailStudent.recentRecords" style="width: 100%">
            <el-table-column prop="date" label="日期" width="120"></el-table-column>
            <el-table-column prop="category" label="分类" width="120"></el-table-column>
            <el-table-column prop="questionCount" label="做题数" width="100"></el-table-column>
            <el-table-column prop="correctCount" label="正确数" width="100"></el-table-column>
            <el-table-column prop="studyTime" label="学习时长" width="120"></el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'AdminStudents',
  data() {
    return {
      searchKeyword: '',
      searchStatus: '',
      searchLevel: '',
      students: [
        {
          id: 1,
          nickname: '张三',
          email: 'zhangsan@example.com',
          avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
          level: 'intermediate',
          studyTime: 3600, // 秒
          questionCount: 150,
          correctRate: 85,
          lastLoginTime: '2024-01-15 10:30:00',
          status: 'active',
          createTime: '2023-12-01 09:00:00',
          streakDays: 7,
          badges: 3,
          progress: [
            { category: 'JavaScript', completed: 45, total: 60 },
            { category: 'Vue.js', completed: 30, total: 40 },
            { category: '数据库', completed: 20, total: 50 }
          ],
          recentRecords: [
            { date: '2024-01-15', category: 'JavaScript', questionCount: 10, correctCount: 8, studyTime: '30分钟' },
            { date: '2024-01-14', category: 'Vue.js', questionCount: 8, correctCount: 7, studyTime: '25分钟' },
            { date: '2024-01-13', category: '数据库', questionCount: 12, correctCount: 9, studyTime: '40分钟' }
          ]
        },
        {
          id: 2,
          nickname: '李四',
          email: 'lisi@example.com',
          avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
          level: 'beginner',
          studyTime: 1800,
          questionCount: 80,
          correctRate: 72,
          lastLoginTime: '2024-01-14 15:20:00',
          status: 'active',
          createTime: '2024-01-01 14:30:00',
          streakDays: 3,
          badges: 1,
          progress: [
            { category: 'JavaScript', completed: 20, total: 60 },
            { category: 'Vue.js', completed: 10, total: 40 }
          ],
          recentRecords: [
            { date: '2024-01-14', category: 'JavaScript', questionCount: 8, correctCount: 6, studyTime: '20分钟' },
            { date: '2024-01-13', category: 'Vue.js', questionCount: 6, correctCount: 4, studyTime: '15分钟' }
          ]
        },
        {
          id: 3,
          nickname: '王五',
          email: 'wangwu@example.com',
          avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
          level: 'advanced',
          studyTime: 7200,
          questionCount: 300,
          correctRate: 92,
          lastLoginTime: '2024-01-15 08:45:00',
          status: 'banned',
          createTime: '2023-10-15 16:20:00',
          streakDays: 15,
          badges: 8,
          progress: [
            { category: 'JavaScript', completed: 60, total: 60 },
            { category: 'Vue.js', completed: 40, total: 40 },
            { category: '数据库', completed: 45, total: 50 }
          ],
          recentRecords: [
            { date: '2024-01-15', category: '数据库', questionCount: 15, correctCount: 14, studyTime: '45分钟' },
            { date: '2024-01-14', category: 'JavaScript', questionCount: 12, correctCount: 11, studyTime: '35分钟' }
          ]
        }
      ],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: '新增学员',
      studentForm: {
        id: null,
        nickname: '',
        email: '',
        password: '',
        avatar: '',
        level: 'beginner',
        status: 'active',
        remark: ''
      },
      studentRules: {
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        level: [
          { required: true, message: '请选择等级', trigger: 'change' }
        ]
      },
      detailDialogVisible: false,
      detailStudent: null
    }
  },
  computed: {
    filteredStudents() {
      let result = this.students;
      
      if (this.searchKeyword) {
        result = result.filter(s => 
          s.nickname.toLowerCase().includes(this.searchKeyword.toLowerCase()) ||
          s.email.toLowerCase().includes(this.searchKeyword.toLowerCase())
        );
      }
      
      if (this.searchStatus) {
        result = result.filter(s => s.status === this.searchStatus);
      }
      
      if (this.searchLevel) {
        result = result.filter(s => s.level === this.searchLevel);
      }
      
      return result;
    }
  },
  watch: {
    filteredStudents: {
      handler(newVal) {
        this.total = newVal.length;
      },
      immediate: true
    }
  },
  methods: {
    getLevelTagType(level) {
      const levelMap = {
        beginner: 'info',
        intermediate: 'warning',
        advanced: 'success'
      };
      return levelMap[level] || 'info';
    },
    getLevelText(level) {
      const levelMap = {
        beginner: '新手',
        intermediate: '进阶',
        advanced: '高级'
      };
      return levelMap[level] || level;
    },
    formatStudyTime(seconds) {
      const hours = Math.floor(seconds / 3600);
      const minutes = Math.floor((seconds % 3600) / 60);
      if (hours > 0) {
        return `${hours}小时${minutes}分钟`;
      }
      return `${minutes}分钟`;
    },
    handleSearch() {
      // 搜索逻辑已在 computed 中处理
    },
    resetSearch() {
      this.searchKeyword = '';
      this.searchStatus = '';
      this.searchLevel = '';
    },
    handleSizeChange(val) {
      this.pageSize = val;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    showAddDialog() {
      this.dialogTitle = '新增学员';
      this.studentForm = {
        id: null,
        nickname: '',
        email: '',
        password: '',
        avatar: '',
        level: 'beginner',
        status: 'active',
        remark: ''
      };
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.dialogTitle = '编辑学员';
      this.studentForm = { ...row };
      this.dialogVisible = true;
    },
    handleToggleStatus(row) {
      const action = row.status === 'active' ? '封禁' : '启用';
      this.$confirm(`确定要${action}这个学员吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 这里应该调用API
        row.status = row.status === 'active' ? 'banned' : 'active';
        this.$message.success(`${action}成功`);
      }).catch(() => {
        this.$message.info('已取消操作');
      });
    },
    handleViewDetail(row) {
      this.detailStudent = row;
      this.detailDialogVisible = true;
    },
    handleSubmit() {
      this.$refs.studentForm.validate((valid) => {
        if (valid) {
          // 这里应该调用保存API
          this.$message.success(this.studentForm.id ? '更新成功' : '添加成功');
          this.dialogVisible = false;
          this.loadStudents();
        }
      });
    },
    handleAvatarSuccess(res, file) {
      this.studentForm.avatar = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    loadStudents() {
      // 这里应该调用获取学员列表API
      console.log('加载学员列表');
    }
  }
}
</script>

<style scoped>
.students {
  padding: 20px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.student-detail .detail-section {
  margin-bottom: 20px;
}

.student-detail .detail-section h4 {
  margin-bottom: 15px;
  color: #303133;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 8px;
}

.student-detail .detail-section p {
  margin: 8px 0;
  color: #606266;
}
</style>
